package com.bana.sys.socket;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 异步通知
 * @author Administrator
 *
 */
public class NoticeHandler {
	
	/**
	 * 表示此次等待是否结束
	 */
	private boolean isCompleted;
	
	/**
	 * 等待的集群协议编号
	 */
	private int protocolId;
	
	/**
	 * 发送时的时间戳
	 */
	private long timeStamp;

	private int port;
	private int controllerId;
	private int controllerProtocolId;

	/**
	 * 接收字节流
	 */
	private byte[] buffer;
	
	/**
	 * 同步锁
	 */
	private Lock lock = new ReentrantLock();

	/**
	 * 条件变量
	 */
	private Condition  condition  = lock.newCondition();
	
	/**
	 * 构造函数
	 * @param protocolId 等待的集群协议编号
	 * @param timeStamp 发送时的时间戳
	 */
	public NoticeHandler(int protocolId, long timeStamp,int port,int controllerId,int controllerProtocolId)
	{
		this.isCompleted=false;
		this.protocolId =protocolId;
		this.timeStamp=timeStamp;
		this.port=port;
		this.controllerId=controllerId;
		this.controllerProtocolId=controllerProtocolId;
	}
	
	/**
	 * 获取异步等待是否完成
	 * @return 异步等待是否完成
	 */
	public boolean getIsCompleted()
	{
		return isCompleted;
	}
	
	/**
	 * 获取等待的集群协议编号
	 * @return 等待的集群协议编号
	 */
	public int getProtocolId()
	{
		return protocolId;
	}
	
	/**
	 * 获取发送时的时间戳
	 * @return 发送时的时间戳
	 */
	public long getTimeStamp()
	{
		return timeStamp;
	}

	/**
	 * 获取接收字节流
	 * @return 接收字节流
	 */
	public byte[] getBuffer() {
		return buffer;
	}

	/**
	 * 等待响应
	 * @param time 超时时间
	 * @return 返回true表示等待成功，返回false表示等待失败
	 */
	public boolean await(int time)
	{
		this.lock.lock();
		try {
			boolean b=condition.await(time, TimeUnit.MILLISECONDS);
			this.isCompleted=true;
			return b;
		} catch (InterruptedException e) {
			this.isCompleted=true;
			return false;
		}
		finally
		{
			this.lock.unlock();
		}
	}
	
	/**
	 * 通知协议已经收到等待协议
	 */
	public void handle(byte[] buffer)
	{
		this.buffer=buffer;
		this.lock.lock();
		this.condition.signalAll();
		this.lock.unlock();
	}

	public int getPort() {
		return port;
	}


	public int getControllerId() {
		return controllerId;
	}

	public int getControllerProtocolId() {
		return controllerProtocolId;
	}

}
